package cn.kone.base.controller;


import cn.kone.base.utlis.R;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/minio")
public class MinIoController {

    private static final String ACCESSKEY = "minioadmin";
    private static final String SECREKEY = "minioadmin123?";
    private static final String ADDRESS = "http://101.35.235.40:9090";
    private static final String BUCKETNAME = "wh-java1031";


    //上传文件
    @PostMapping
    public R<String> upload(@RequestPart("file") MultipartFile file) {
        try {
            // 构建一个Minio客户端
            MinioClient minioClient = MinioClient.builder()
                    //创建容器时指定的账号
                    .credentials(MinIoController.ACCESSKEY, MinIoController.SECREKEY)
                    //上传地址
                    .endpoint(MinIoController.ADDRESS).build();

            //处理文件名
            String oName = file.getOriginalFilename();
            String fileName = "111喻瑜上传的图片" + System.currentTimeMillis() + oName.substring(oName.lastIndexOf("."));

            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(fileName)    //文件名
                    .bucket(MinIoController.BUCKETNAME)  //存储目录名
                    .stream(file.getInputStream(), file.getSize(), -1).build(); //文件流，以及大小，-1代表不分片

            //执行上传
            minioClient.putObject(putObjectArgs);
            return R.ok("上传成功", fileName);

        } catch (Exception e) {
            return R.fail();
        }
    }

    //删除文件
    @DeleteMapping("/{name}")
    public R<Void> delete(@PathVariable("name") String name) {
        try {
            // 构建一个Minio客户端
            MinioClient minioClient = MinioClient.builder()
                    //创建容器时指定的账号
                    .credentials(MinIoController.ACCESSKEY, MinIoController.SECREKEY)
                    //上传地址
                    .endpoint(MinIoController.ADDRESS).build();

            minioClient.removeObject(MinIoController.BUCKETNAME, name);
            return R.ok();
        } catch (Exception e) {
            return R.fail();
        }
    }
}